<template>
  <view class="order-list-page">
    <!-- [修改] 顶部Tab筛选栏 -->
    <view class="tabs-container">
      <scroll-view class="tabs-scroll-view" :scroll-x="true" :show-scrollbar="false">
        <view class="tabs">
          <view
            v-for="tab in tabs"
            :key="tab.status"
            class="tab-item"
            :class="{ active: activeTab === tab.status }"
            @click="changeTab(tab.status)"
          >
            {{ tab.name }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 订单列表 -->
    <scroll-view class="scroll-content" :scroll-y="true">
      <view v-if="filteredOrders.length > 0" class="order-list">
        <view v-for="order in filteredOrders" :key="order.id" class="order-card">
          <view class="card-header">
            <text class="order-time">{{ order.time }}</text>
            <text class="order-status" :style="{ color: getStatusColor(order.status) }">{{ order.statusText }}</text>
          </view>
          <view class="card-body">
            <view class="service-info">
              <text class="title">{{ order.service }}</text>
              <text class="price">订金: ¥{{ order.price.toFixed(2) }}</text>
            </view>
          </view>
          <view class="card-footer">
            <!-- [核心修改] 动态按钮区域 -->
            <button v-if="order.status === 'unpaid_deposit'" class="action-btn btn-secondary" @click="cancelOrder(order.id)">取消订单</button>
            <button v-if="order.status === 'unpaid_deposit'" class="action-btn btn-primary" @click="payOrder(order.id, 'deposit')">支付订金</button>
            
            <button v-if="order.status === 'unpaid_final'" class="action-btn btn-primary" @click="payOrder(order.id, 'final')">支付尾款</button>
            
            <button v-if="order.status === 'reviewing'" class="action-btn btn-primary" @click="reviewOrder(order)">去评价</button>
            
            <button v-if="order.status === 'completed' || order.status === 'cancelled'" class="action-btn btn-secondary" @click="deleteOrder(order.id)">删除订单</button>
            
            <!-- 待服务 和 服务中 状态通常没有操作按钮，或者有一个“联系客服”的按钮 -->
            <button v-if="order.status === 'servicing' || order.status === 'in_service'" class="action-btn btn-secondary" @click="contactService">联系客服</button>
          </view>
        </view>
      </view>
      <!-- 空状态 -->
      <view v-else class="empty-state">
        <image class="empty-image" src="/static/icons/empty-order.svg" mode="widthFix"></image>
        <text class="empty-text">暂无相关订单</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad, onPullDownRefresh, onShow } from '@dcloudio/uni-app';
import { request } from '@/utils/request.js';

// [修改] 更新Tabs
const tabs = [
  { name: '全部', status: 'all' },
  { name: '待付订金', status: 'unpaid_deposit' },
  { name: '待服务', status: 'servicing' },
  { name: '服务中', status: 'in_service' },
  { name: '待付尾款', status: 'unpaid_final' },
  { name: '待评价', status: 'reviewing' },
  { name: '已完成', status: 'completed' },
];
const activeTab = ref('all');
const allOrders = ref([]);

// [修改] 更新状态映射
const statusMap = {
  '待付订金': 'unpaid_deposit',
  '待服务': 'servicing',
  '服务中': 'in_service',
  '待付尾款': 'unpaid_final',
  '待评价': 'reviewing',
  '已完成': 'completed',
  '已取消': 'cancelled',
};

const filteredOrders = computed(() => {
  if (activeTab.value === 'all') return allOrders.value;
  return allOrders.value.filter(order => order.status === activeTab.value);
});

// ---- API Methods ----
const fetchOrders = async () => {
  try {
    const userId = uni.getStorageSync('userId');
    if (!userId) {
      allOrders.value = [];
      return;
    }

    const data = await request({ url: '/orders', method: 'POST', data: { userId } });
    
    allOrders.value = data.map(order => ({
      id: order.orderId,
      time: order.orderDatetime,
      service: order.serviceMainName,
      price: order.orderStartMoney, // 订金
      finalPrice: order.orderEndMoney, // 尾款
      statusText: order.orderStatus,
      status: statusMap[order.orderStatus] || 'unknown',
      serviceId: order.serviceId,
    }));
  } catch (error) {
    console.error("获取订单列表失败:", error);
    allOrders.value = [];
  }
};

// ---- Event Handlers ----
const changeTab = (status) => { activeTab.value = status; };

const getStatusColor = (status) => {
  const colorMap = {
    unpaid_deposit: '#F56C6C', // 红色
    unpaid_final: '#F56C6C',   // 红色
    reviewing: '#4A90E2',      // 主题蓝
    servicing: '#E6A23C',     // 橙色
    in_service: '#E6A23C',    // 橙色
    completed: '#888888',     // 灰色
  };
  return colorMap[status] || '#333';
};

// [修改] 支付方法增加类型区分
const payOrder = (id, type) => {
  console.log(`支付订单 ${id} 的 ${type}`);
  // 跳转到支付页，可以带上类型参数
  uni.navigateTo({ url: `/pages/order-payment/order-payment?orderId=${id}&payType=${type}` });
};

const reviewOrder = (order) => {
  const orderStr = encodeURIComponent(JSON.stringify(order));
  uni.navigateTo({ url: `/pages/user/order-review?order=${orderStr}` });
};
const deleteOrder = (id) => {
    // TODO: 调用删除订单接口
    uni.showModal({
        title: '提示',
        content: '确定要删除此订单吗？',
        success: res => { if (res.confirm) { /* ... API Call ... */ } }
    })
};
// [修改] cancelOrder 方法
const cancelOrder = (id) => {
  uni.showModal({
    title: '提示',
    content: '确定要取消这个订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '正在取消...' });
          
          await request({
            url: `/my/orders/${id}/cancel`, // 调用新的取消接口
            method: 'PUT', // 使用 PUT 方法
            // 该接口不需要请求体，但需要请求头，request.js 会自动添加
          });
          
          uni.hideLoading();
          uni.showToast({ title: '订单已取消', icon: 'none' });

          // [方法一：乐观更新] 直接在前端修改状态，UI响应最快
          const index = allOrders.value.findIndex(o => o.id === id);
          if (index !== -1) {
            allOrders.value[index].status = 'cancelled';
            allOrders.value[index].statusText = '已取消';
          }
          
          // [方法二：重新拉取] 保证数据绝对同步，但会有一个短暂的加载过程
          // fetchOrders();

        } catch (error) {
          uni.hideLoading();
          console.error("取消订单失败:", error);
        }
      }
    }
  });
};
// ---- Lifecycle ----
onLoad((options) => {
  // 从个人中心页跳转过来时，根据状态切换Tab
  // 我们需要一个反向映射来找到正确的status key
  const reverseStatusMap = {
      'unpaid': 'unpaid_deposit',
      'servicing': 'servicing',
      'reviewing': 'reviewing',
      'completed': 'completed'
  };
  const targetStatus = reverseStatusMap[options.status];
  if (targetStatus) {
    activeTab.value = targetStatus;
  }
});

onShow(() => { fetchOrders(); });
onPullDownRefresh(() => { fetchOrders().finally(() => uni.stopPullDownRefresh()); });
</script>

<style lang="scss" scoped>
.order-list-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: $uni-bg-color;
}

.tabs-container {
  background-color: $uni-bg-color-white;
  border-bottom: 1px solid $uni-border-color;
  flex-shrink: 0;
}

.tabs {
  display: flex;
  justify-content: space-around;
  .tab-item {
    padding: 24rpx 0;
    font-size: 30rpx;
    color: $uni-text-color-light;
    position: relative;
    &.active {
      color: $uni-primary;
      font-weight: 500;
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 6rpx;
        background-color: $uni-primary;
        border-radius: 4rpx;
      }
    }
  }
}

.scroll-content {
  flex: 1;
  height: 0; // flex布局下，让scroll-view正确占据剩余空间
}

.order-list {
  padding: 30rpx;
}

.order-card {
  background-color: $uni-bg-color-white;
  border-radius: 24rpx;
  margin-bottom: 30rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.06);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20rpx;
    border-bottom: 1px dashed $uni-border-color;
    margin-bottom: 30rpx;
    
    .order-time { font-size: 26rpx; color: $uni-text-color-light; }
    .order-status { font-size: 28rpx; font-weight: 500; }
  }
  
  .card-body {
    display: flex;
    justify-content: space-between; // 两端对齐
    align-items: center;
    margin-bottom: 30rpx;
    .service-info {
        flex: 1;
        .title { font-size: 30rpx; font-weight: 500; }
        .price { font-size: 28rpx; color: $uni-text-color-light; margin-top: 10rpx;}
    }
  }
  
  .card-footer {
    display: flex;
    justify-content: flex-end; // 按钮靠右
    gap: 20rpx;
    
    .action-btn {
      padding: 0 32rpx;
      height: 60rpx;
      line-height: 60rpx;
      border-radius: 30rpx;
      font-size: 26rpx;
      font-weight: 500;
      margin: 0; // 清除默认margin
      &::after { border: none; } // 清除默认边框
    }
    .btn-primary {
      background-color: $uni-primary;
      color: white;
    }
    .btn-secondary {
      background-color: $uni-bg-color-white;
      color: $uni-text-color;
      border: 1px solid $uni-border-color;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 200rpx;
  .empty-image {
    width: 200rpx;
    margin-bottom: 40rpx;
  }
  .empty-text {
    font-size: 30rpx;
    color: $uni-text-color-light;
  }
}
</style>